package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.AccidentRecordDao;
import com.wlhse.entity.AccidentRecordPojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.AccidentRecordService;
import com.wlhse.util.HashUtil;
import com.wlhse.util.R;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;

@Service
public class AccidentRecordServiceImpl implements AccidentRecordService {

    @Resource
    private AccidentRecordDao accidentRecordDao;

    @Override
    public R addAccidentRecord(AccidentRecordPojo pojo) {
        String tmp = pojo.getAccidentRecordName() + pojo.getCheckDate() + pojo.getAddress();
        String hash = HashUtil.hash(tmp);
        pojo.setHash(hash);
        if (accidentRecordDao.addAccidentRecord(pojo) <= 0)
            throw new WLHSException("新增失败");
        return R.ok();
    }

    @Override
    public R deleteAccidentRecord(int id) {
        if (accidentRecordDao.deleteAccidentRecord(id) <= 0)
            throw new WLHSException("删除失败");
        return R.ok();
    }

    @Override
    public R updateAccidentRecord(AccidentRecordPojo pojo) {
        if (accidentRecordDao.updateAccidentRecord(pojo) <= 0)
            throw new WLHSException("更新失败");
        return R.ok();
    }

    //查 By Id
    @Override
    public R queryAccidentRecordsById(int id) {
        AccidentRecordPojo pojo = accidentRecordDao.queryAccidentRecordsById(id, CodeDict.getRESOURCES_URL());
        Map<String, Object> map = new HashMap<>();
        map.put("data", pojo);
        return R.ok(map);
    }

    // 条件分页查
    @Override
    public String queryAccidentRecordsByContiton(AccidentRecordPojo accidentRecordPojo) {
        accidentRecordPojo.setUrl(CodeDict.getRESOURCES_URL());
        if (StringUtils.isNotBlank(accidentRecordPojo.getStartDate()) && StringUtils.isBlank(accidentRecordPojo.getEndDate())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            accidentRecordPojo.setEndDate(df.format(new Date()));// new Date()为获取当前系统时间
        }
        if ("all".equals(accidentRecordPojo.getType()))
            return NR.r(accidentRecordDao.queryAccidentRecordsByContiton(accidentRecordPojo));
        int total = accidentRecordDao.queryTotal(accidentRecordPojo);
        int pageIdx = accidentRecordPojo.getPageIdx();
        PageHelper.startPage(pageIdx, accidentRecordPojo.getPageSize());
        List<AccidentRecordPojo> list = accidentRecordDao.queryAccidentRecordsByContiton(accidentRecordPojo);
        return NR.r(list, total, pageIdx);
    }
}
